import { App } from 'vue'
import { createI18n } from 'vue-i18n'

//自己的包
import zh from './lang/cn'
import en from './lang/en'

//element语言包
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import English from 'element-plus/dist/locale/en.mjs'

const messages = {
  cn: {
    el: zhCn,
    ...zh
  },
  us: {
    el: English,
    ...en
  }
}
// 确保即使localStorage不可用也能正确初始化语言设置
let defaultLocale = 'cn';
try {
  const storedLang = localStorage.getItem('lang');
  if (storedLang) {
    defaultLocale = storedLang;
  }
} catch (error) {
  console.error('无法访问localStorage:', error);
}

const i18n = createI18n({
  legacy: false,
  locale: defaultLocale, // 使用安全获取的语言设置
  fallbackLocale: 'cn', // 兜底语言
  messages
})

export default i18n

export function setupI18n(app: App) {
  app.use(i18n)
}